package com.resource.provider.config;

import com.resource.provider.exception.ParameterException;
import com.resource.provider.exception.PermissionException;
import com.resource.provider.httpService.UserHttpService;
import com.resource.provider.util.TokenUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 这个aop用于检查用户库是否存在
 *
 * @author 陈睿
 * @date 2020/4/30
 */
@Aspect
@Component
@Order(1)
public class CropIdExistenceAop {
    private Logger log = LoggerFactory.getLogger(CropIdExistenceAop.class);

    @Autowired
    private UserHttpService userHttpService;

    /**
     * 增强方法 用于token认证
     * @param joinPoint 连接点对象
     * @return
     */
   // @Around("execution(* com.resource.provider.serviceimpl.*ServiceImpl.*(..))")
    public Object isExistenceCropId(ProceedingJoinPoint joinPoint) throws Throwable{
        Map<String, Object> nameAndValue = getNameAndValue(joinPoint);
        log.info("aop拦截，当前方法：【{}】，参数:{}", joinPoint.getSignature(), nameAndValue);
        String token;

        JSONObject userInfo = null;

        //鉴权
        Object tokenString = nameAndValue.get("token");
        if (tokenString != null && StringUtils.isNotBlank(tokenString.toString())) {
            token = ((String) tokenString);
            JSONObject json;
            // 调用鉴权工具类获取json对象
            boolean flag = token.startsWith("user-admin-info");
            Long currentTimeMillis = System.currentTimeMillis();

            if (!flag) {
                json = TokenUtil.getPrivilegeTokenRPC(token);
                log.info("rpc用户信息：{}", json);

            } else {
                //先默认从token中将cropId拿出来
                userInfo = userHttpService.getUserByAccessToken(token);
                if (userInfo == null) {
                    throw new PermissionException("-1", "鉴权失败,鉴权系统繁忙，请稍后再试");
                }
                log.info("用户信息：{}", userInfo);
                if (!"0".equals(userInfo.getString("code"))) {
                    throw new PermissionException(userInfo.getString("code"), userInfo.getString("message"));
                }

            }

            System.out.println("token验证耗时:" + (System.currentTimeMillis() - currentTimeMillis));

        } else {
            throw new ParameterException("40002", "Token为空或Token失效");
        }

        return joinPoint.proceed();
     
    }

    public static void main(String[] args) {
        String token = "xxhpt593b84ae74fc1376e8751d8bb2579bf8";

    }

    /**
     * 获取参数名与参数值的映射表
     *
     * @param joinPoint
     * @return
     */
    private Map<String, Object> getNameAndValue(ProceedingJoinPoint joinPoint) {
        Map<String, Object> param = new HashMap<>();
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        //2.最关键的一步:通过这获取到方法的所有参数名称的字符串数组
        String[] parameterNames = methodSignature.getParameterNames();
        if (parameterNames.length < 1) {
            return param;
        }
        for (int i = 0; i < parameterNames.length; i++) {
            param.put(parameterNames[i], args[i]);
        }

        return param;
    }




}
